package com.example.config;

import com.example.filter.JwtAuthenticationFilter;
import com.example.filter.LoggingFilter;
import javax.servlet.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 过滤器配置类
 * 配置JWT认证过滤器的注册和执行顺序
 */
@Configuration
public class FilterConfig {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Autowired
    private LoggingFilter loggingFilter;

    /**
     * 注册日志过滤器（最高优先级）
     */
    @Bean
    public FilterRegistrationBean<Filter> loggingFilterRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(loggingFilter);
        
        // 拦截所有请求
        registration.addUrlPatterns("/*");
        
        // 最高优先级，确保日志记录在最外层
        registration.setOrder(0);
        registration.setName("loggingFilter");
        
        System.out.println("日志过滤器已注册，拦截路径: /*，优先级: 0");
        
        return registration;
    }

    /**
     * 注册JWT认证过滤器
     */
    @Bean
    public FilterRegistrationBean<JwtAuthenticationFilter> jwtFilterRegistration() {
        FilterRegistrationBean<JwtAuthenticationFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(jwtAuthenticationFilter);
        
        // 设置过滤器拦截的URL模式
        registration.addUrlPatterns("/api/*");  // 只拦截以/api/开头的请求
        
        // 设置过滤器执行顺序（数字越小优先级越高）
        registration.setOrder(1);
        
        // 设置过滤器名称
        registration.setName("jwtAuthenticationFilter");
        
        System.out.println("JWT认证过滤器已注册，拦截路径: /api/*");
        
        return registration;
    }
}
